/*
 * Copyright (c) 2012 SUBSECRETARIA DEFENSORIA DEL ESPACIO PUBLICO - SDEP.
 * All Rights Reserved.
 * This software is the confidential and proprietary information of SDEP
 * Developed By CONSTULT-SOFT S.A, Development Team 2012.
 *
 */
package co.gov.medellin.sdep.sisdep.domain.cco;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

import co.gov.medellin.sdep.sisdep.domain.BaseController;
import co.gov.medellin.sdep.sisdep.domain.MessageModalWindowController;
import co.gov.medellin.sdep.sisdep.cco.exception.CentroComercialException;
import co.gov.medellin.sdep.sisdep.cco.exception.LocalException;
import co.gov.medellin.sdep.sisdep.cco.exception.LocalRuntimeException;
import co.gov.medellin.sdep.sisdep.cco.exception.SolicitudLocalRuntimeException;
import co.gov.medellin.sdep.sisdep.cco.exception.descriptor.SolicitudLocalMessageDescriptor;
import co.gov.medellin.sdep.sisdep.cco.service.ICentroComercialService;
import co.gov.medellin.sdep.sisdep.cco.service.ILocalService;
import co.gov.medellin.sdep.sisdep.common.AppConstants;
import co.gov.medellin.sdep.sisdep.common.message.MessageDescriptorConstant;
import co.gov.medellin.sdep.sisdep.model.Local;

/**
 * @author Usuario
 * 
 */
public class LocalController extends BaseController implements
		Serializable {

	/**
	 * generated serial version
	 */
	private static final long serialVersionUID = -3285110767384990403L;

	/** bean para el manejo del formulario de busqueda Local */
	private Local localSearch = new Local();

	/** Objeto contenedor del listado de Local luego de una consulta. */
	private transient DataModel localListModel;

	/** bean para el manejo del formulario de creacion/edicion. Local */
	private Local local = new Local();

	/** instancia de servicio localService */
	private ILocalService localService;

	LocalInventarioController localInventarioController;
	
	/** instancia de servicio centroComercialService */
	private ICentroComercialService centroComercialService;

	/** instancia de servicio feriaDecFormVentaService */
	private List listaCentrosComerciales;
	/**
	 * Constructor por defecto, inicializa los elemento basicos del Controlador
	 */
	public LocalController() {
		this.localListModel = new ListDataModel();
	}
	// --------------------------------------------------------------------
	// --- metodos para atender acciones init()
	// --------------------------------------------------------------------

	/**
	 * 
	 * @return String
	 */
	public String searchLocalByKey() {
		String msg = "";
		try {
			List valores = null;
			valores = getLocalService().load(1, 10,
					this.localSearch);
			this.localListModel.setWrappedData(valores);
		} catch (Exception e) {
			msg = e.getMessage();
			e.printStackTrace(System.err);
		}
		if (this.localListModel.getWrappedData() == null) {
			msg = AppConstants.NO_RECORDS_FOUND;
		} else {
			if (((List) this.localListModel.getWrappedData()).isEmpty()) {
				msg = AppConstants.NO_RECORDS_FOUND;
			}
		}
		((MessageModalWindowController) getBean("messageController"))
				.setSuccessMessage(msg, null, null);
		return AppConstants.LOCAL_SEARCH_VIEW;
	}
	
	/**
	 * 
	 * @return String
	 */
	public String searchLocalByNumeroLocal() {
		String msg = "";
		try {
			List valores = null;
			valores = getLocalService().loadByNumeroLocal(1, 10,
					this.localSearch);
			this.localListModel.setWrappedData(valores);
		} catch (Exception e) {
			msg = e.getMessage();
			e.printStackTrace(System.err);
		}
		if (this.localListModel.getWrappedData() == null) {
			msg = AppConstants.NO_RECORDS_FOUND;
		} else {
			if (((List) this.localListModel.getWrappedData()).isEmpty()) {
				msg = AppConstants.NO_RECORDS_FOUND;
			}
		}
		((MessageModalWindowController) getBean("messageController"))
				.setSuccessMessage(msg, null, null);
		return AppConstants.LOCAL_SEARCH_VIEW;
	}	

  /**
	 * Metodo que permite espeficicar la funcionalidad para la gestion [Crear / Actualizar] de un elmento tipo:
	 * Local.
	 *     
	 * @author programador.java@consult-soft.com  05-06-2012
	 * @return String Vista a la cual debe retornar
	 * 	 
	 */
	public String manage() {
		String returnView = AppConstants.LOCAL_SEARCH_VIEW;
		if(this.local.getId() == null) {
       returnView = create();
		} else {
       returnView = update();
		}
		return returnView;
	}

	/**
	 * 
	 * @return
	 */
	public String create() {
		String msg = AppConstants.DEFAULT_ERROR;
		try {
			if (this.local.getId() == null) {
				local.setIdCentroComercial(new Long(local.getIdCentroComercialStr()));
				getLocalService().insert(this.local);
				msg = AppConstants.SUCCESS_CREATE;
			}
		} catch (LocalException e) {
			msg = e.getEndUserMessage();
			e.printStackTrace(System.err);
		} catch (LocalRuntimeException e) {
			msg = e.getEndUserMessage();
			e.printStackTrace(System.err);
		}
		((MessageModalWindowController) getBean(AppConstants.MESSAGE_CONTROLLER_BEAN))
				.setSuccessMessage("- local " + msg, null, null);
		return AppConstants.LOCAL_SEARCH_VIEW;
	}

	/**
	 * 
	 * @return
	 */
	public String update() {
		String msg = AppConstants.DEFAULT_ERROR;
		try {
			if (this.local.getId() != null) {		
				local.setIdCentroComercial(new Long(local.getIdCentroComercialStr()));
				getLocalService().update(this.local);
				msg = AppConstants.SUCCESS_UPDATE;
			}
		} catch (LocalException e) {
			msg = e.getEndUserMessage();
			e.printStackTrace(System.err);
		} catch (LocalRuntimeException e) {
			msg = e.getEndUserMessage();
			e.printStackTrace(System.err);
		}
		((MessageModalWindowController) getBean(AppConstants.MESSAGE_CONTROLLER_BEAN))
				.setSuccessMessage("- Valor Tipo Maestra " + msg, null, null);
		return AppConstants.LOCAL_SEARCH_VIEW;
	}
	

	/**
	 * @return 
	 * 
	 */
	public final List listaLocales() throws LocalException {
		try{
			//return getSolicitudLocalDAO().getAllSolicitudLocalPaginated(start, max, criteria);
			return getLocalService().listaLocales();
		}catch (Exception e) {
			Object [] infoError = null;
			throw new SolicitudLocalRuntimeException(new SolicitudLocalMessageDescriptor(MessageDescriptorConstant.RETRIEVE), infoError, e);
		}
	}		

	/**
	 * @return 
	 * 
	 */
	public final List listaLocalesPorCCO(Long idCentroComercial) throws LocalException {
		try{
			//return getSolicitudLocalDAO().getAllSolicitudLocalPaginated(start, max, criteria);
			return getLocalService().listaLocalesPorCCO(idCentroComercial);
		}catch (Exception e) {
			Object [] infoError = null;
			throw new SolicitudLocalRuntimeException(new SolicitudLocalMessageDescriptor(MessageDescriptorConstant.RETRIEVE), infoError, e);
		}
	}		

	// --------------------------------------------------------------------
	// --- metodos para atender acciones end()
	// --------------------------------------------------------------------

	// --------------------------------------------------------------------
	// --- metodos para atender reglas de navegacion init()
	// --------------------------------------------------------------------

	/**
	 * 
	 */
	public String createLocal() {
		local = new Local();
		local.setId(null);
		local.setUsuarioCrea(getLoggedUserID());		
		local.setEstado("ACTIVO");
		listaCentrosComerciales = new ArrayList();
		try {
			if(getCentroComercialService().listaCentrosComerciales() != null){
				for(int i = 0; i<getCentroComercialService().listaCentrosComerciales().size();i++){			
					List listaT = new ArrayList();
					String registro[];
					listaT = (List)getCentroComercialService().listaCentrosComerciales().get(i);	
					registro = (String[])listaT.get(0);
					listaCentrosComerciales.add(new SelectItem(registro[0].toString(),registro[1].toString()));
					listaT = null;
					registro=null;
				}	
			}
		} catch (CentroComercialException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}			
		return AppConstants.LOCAL_CREATE_VIEW;
	}

	/**
	 * 
	 * @return
	 */
	public String updateLocal() {
		Map params = getExternalContext().getRequestParameterMap();
		String localDataIndex = (String) params
				.get("localDataIndex");
		this.local = (Local) ((List) this.localListModel
				.getWrappedData())
				.get(Integer.parseInt(localDataIndex));
		listaCentrosComerciales = new ArrayList();
		try {
			if(getCentroComercialService().listaCentrosComerciales() != null){
				for(int i = 0; i<getCentroComercialService().listaCentrosComerciales().size();i++){			
					List listaT = new ArrayList();
					String registro[];
					listaT = (List)getCentroComercialService().listaCentrosComerciales().get(i);	
					registro = (String[])listaT.get(0);
					listaCentrosComerciales.add(new SelectItem(registro[0].toString(),registro[1].toString()));
					listaT = null;
					registro=null;
				}	
			}
		} catch (CentroComercialException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}			
		return AppConstants.LOCAL_UPDATE_VIEW;
	}


	/**
	 * 
	 * @return
	 */
	public String inventarioLocal() {
		Map params = getExternalContext().getRequestParameterMap();
		String localDataIndex = (String) params
				.get("localDataIndex");
		this.local = (Local) ((List) this.localListModel
				.getWrappedData())
				.get(Integer.parseInt(localDataIndex));
		
		getLocalInventarioController().localInventarioSearch.setIdLocalStr(local.getId().toString());
		getLocalInventarioController().searchLocalInventarioByKey();
		return AppConstants.LOCAL_INVENTARIO_SEARCH_VIEW;
	}
	
	/**
	 * 
	 * @return
	 */
	public String cancelLocal() {
		return AppConstants.LOCAL_SEARCH_VIEW;
	}

	// --------------------------------------------------------------------
	// --- metodos para atender reglas de navegacion end()
	// --------------------------------------------------------------------

	// --------------------------------------------------------------------
	// --- getters and setters init()
	// --------------------------------------------------------------------

	/**
	 * 
	 */
	public Local getLocalSearch() {
		return localSearch;
	}

	/**
	 * 
	 * @param localSearch
	 */
	public void setlocalSearch(Local localSearch) {
		this.localSearch = localSearch;
	}

	/**
	 * 
	 * @return
	 */
	public DataModel getlocalListModel() {
		return localListModel;
	}

	/**
	 * 
	 * @param localListModel
	 */
	public void setlocalListModel(DataModel localListModel) {
		this.localListModel = localListModel;
	}

	/**
	 * 
	 * @return
	 */
	public Local getLocal() {
		return local;
	}

	/**
	 * 
	 * @param local
	 */
	public void setlocal(Local local) {
		this.local = local;
	}

	/**
	 * obtencion del servicio localService
	 * 
	 * @return
	 */
	public ILocalService getLocalService() {
		return localService;
	}

	/**
	 * establecimiento del servicio localService, la inyeccion de la
	 * dependencia la cubre SpringFramework
	 * 
	 * @param localService
	 */
	public void setLocalService(
			ILocalService localService) {
		this.localService = localService;
	}

	public LocalInventarioController getLocalInventarioController() {
		return localInventarioController;
	}

	public void setLocalInventarioController(
			LocalInventarioController localInventarioController) {
		this.localInventarioController = localInventarioController;
	}

	public ICentroComercialService getCentroComercialService() {
		return centroComercialService;
	}

	public void setCentroComercialService(
			ICentroComercialService centroComercialService) {
		this.centroComercialService = centroComercialService;
	}

	public List getListaCentrosComerciales() {
		return listaCentrosComerciales;
	}

	public void setListaCentrosComerciales(List listaCentrosComerciales) {
		this.listaCentrosComerciales = listaCentrosComerciales;
	}

	// --------------------------------------------------------------------
	// --- getters and setters end()
	// --------------------------------------------------------------------

}
